package cn.ibizlab.eam.core.extensions.service;

import cn.ibizlab.eam.core.eam_core.domain.EMAsset;
import cn.ibizlab.eam.core.eam_core.service.IEMAssetClearService;
import cn.ibizlab.eam.core.eam_core.service.impl.EMAssetClearServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import cn.ibizlab.eam.core.eam_core.domain.EMAssetClear;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Primary;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 实体[资产清盘记录] 自定义服务对象
 */
@Slf4j
@Primary
@Service("EMAssetClearExService")
public class EMAssetClearExService extends EMAssetClearServiceImpl {

    @Override
    protected Class currentModelClass() {
        return com.baomidou.mybatisplus.core.toolkit.ReflectionKit.getSuperClassGenericType(this.getClass().getSuperclass(), 1);
    }

    /**
     * 自定义行为[Clear]用户扩展
     * @param et
     * @return
     */
    @Override
    @Transactional
    public EMAssetClear clear(EMAssetClear et) {
        // 资产盘点
        // 首先将资产清盘表中的旧资产盘点记录的ISNEW(最新清盘)置为0
        this.update(Wrappers.<EMAssetClear>update().set("ISNEW", 0).eq("ISNEW", 1));
        // 从资产表里面重新统计资产
        List<EMAsset> emAssets = emassetService.list(Wrappers.<EMAsset>query().ne("ASSETSTATE", -1));
        Timestamp currentDate = new Timestamp(System.currentTimeMillis());
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 逐一盘点资产，获得新的资产盘点记录
        List<EMAssetClear> emAssetClears = new ArrayList<>();
        for(EMAsset asset : emAssets){
            EMAssetClear emAssetClear = new EMAssetClear();
            String emAssetClearName = dateFormat.format(currentDate);
            emAssetClearName += asset.getEmassetname() + asset.getAssetcode();
            emAssetClear.setEmassetclearname(emAssetClearName); // 资产清盘记录名称
            emAssetClear.setEmassetid(asset.getEmassetid()); // 资产
            emAssetClear.setAssetchecknum(1); // 盘点清查数量
            emAssetClear.setAssetcheckprice(asset.getOriginalcost()); // 盘点清查金额
            emAssetClear.setAssetclearlct(asset.getAssetlct()); // 使用部门
            emAssetClear.setAssetcleardate(currentDate); // 盘点日期
            emAssetClear.setIsnew(1); // 最新清盘
            emAssetClears.add(emAssetClear);
        }
        // 批量往资产清盘表中插入新的资产盘点记录
        IEMAssetClearService proxy = AopContext.currentProxy()==null ? this : (IEMAssetClearService)AopContext.currentProxy() ;
        proxy.createBatch(emAssetClears);
        return super.clear(et);
    }
}

